package com.wh.message.mq.service.impl;


import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.order.OrderProducer;
import com.wh.common.util.MD5Util;
import com.wh.common.util.Result;
import com.wh.message.mq.in.MqIn;
import com.wh.message.mq.service.AliyunMqMessageService;
import com.wh.message.redis.service.RedisMessageService;
import com.wh.message.utils.HashUtil;
import com.wh.message.utils.ValidatorFactoryUtil;
import com.wh.msg.ResultCode;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Properties;


/**
 * 阿里云消息发送服务，只对消息进行发送，不对消息的内容进行验证，同一条消息在一分钟之内不进行发送
 * @author 谢泽鹏
 * @version V1.0
 * @Package com.wh.message.mq.service.impl
 * @date 2014年10月8日 下午4:02:14
 * @Copyright 个人版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
public class AliyunMqMessageServiceImpl implements AliyunMqMessageService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 消息主题
     */
    private String topIc;

    /**
     * 消息生产者ID
     */
    private String producerId;

    /**
     *
     */
    private String accessKey;

    /**
     *
     */
    private String secretKey;

    /**
     *
     */
    private String oNSAddr;


    private OrderProducer producer;

    @Autowired
    private RedisMessageService redisMessageService;




    @Override
    public Result sendMsg(MqIn in) {
        logger.info("sendMsg阿里MQ推送============开始========");
        logger.info("sendMsg阿里MQ推送，入参,in={}", JSONObject.fromObject(in).toString());
        Result res = new Result();
        try {
            res = ValidatorFactoryUtil.validate(in);
            if(!ResultCode.RES_OK.equals(res.getResCode())){
                logger.info("sendMsg阿里MQ推送，参数校验不通过,result={}",in);
                return res;
            }
            Message msg = new Message(topIc, in.getTag(), in.getBody().getBytes());
            //对1分钟以内相同的内容不进行发送消息队列
            long hashId = HashUtil.crc32Code(msg.getBody());
            String key = "PUBLIC_CODE_MESSAGE_" + MD5Util.getMD5ofStr(in.toString());
            String value = redisMessageService.get(key);
            if(value != null){
                logger.info("sendMsg阿里MQ推送，已经存在此次推送");
                res.setResCode(ResultCode.RES_2010);
            }else {
                redisMessageService.set(key, hashId + "", 60L);
                if (producer == null) {
                    Properties properties = new Properties();
                    // 您在控制台创建的 Producer ID
                    properties.put(PropertyKeyConst.ProducerId, producerId);
                    // AccessKey 阿里云身份验证，在阿里云服务器管理控制台创建
                    properties.put(PropertyKeyConst.AccessKey, accessKey);
                    // SecretKey 阿里云身份验证，在阿里云服务器管理控制台创建
                    properties.put(PropertyKeyConst.SecretKey, secretKey);
                    // 此处以公共云生产环境为例
                    properties.put(PropertyKeyConst.ONSAddr, oNSAddr);
                    producer = ONSFactory.createOrderProducer(properties);
                }
                //当消息服务没有开启时 执行开启
                if (producer.isClosed()) {
                    producer.start();
                }
                msg.setKey(in.getKey());
                SendResult sendResult = producer.send(msg, msg.getKey());
                res.setResCode(ResultCode.RES_OK);
                res.setResult(sendResult.getMessageId());
                logger.info("sendMsg阿里MQ推送============成功res={}", res);
            }
        } catch (Exception e) {
            logger.error("sendMsg阿里MQ推送============出现异常msg={}",e.getMessage());
            e.printStackTrace();
            res.setResCode(ResultCode.RES_ERR);
            res.setResult(e.getMessage());
        }
        logger.info("sendMsg阿里MQ推送============结束===========");
        return res;
    }

    public String getTopIc() {
        return topIc;
    }

    public void setTopIc(String topIc) {
        this.topIc = topIc;
    }

    public String getProducerId() {
        return producerId;
    }

    public void setProducerId(String producerId) {
        this.producerId = producerId;
    }

    public String getAccessKey() {
        return accessKey;
    }

    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public String getoNSAddr() {
        return oNSAddr;
    }

    public void setoNSAddr(String oNSAddr) {
        this.oNSAddr = oNSAddr;
    }

    public OrderProducer getProducer() {
        return producer;
    }

    public void setProducer(OrderProducer producer) {
        this.producer = producer;
    }
}